<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\common\Common;
use app\common\UserService;
use app\model\AdminMoneyLog;
use app\model\Goods;
use app\model\GoodsOrders;
use app\model\Notice;
use app\model\PointGoods;
use app\model\PointGoodsOrders;
use app\model\User;
use app\model\UserCollect;
use app\model\UserCoupon;
use app\model\UserFoot;
use app\model\UserMoneyLog;
use app\model\UserScoreLog;
use app\tool\Random;
use DateInterval;
use DatePeriod;
use DateTime;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use thans\jwt\facade\JWTAuth;
use think\db\Query;
use think\Exception;
use think\facade\Cache;
use think\facade\Config;
use think\facade\Db;
use think\facade\Log;
use think\Request;

class UserController extends BaseController
{
	/**
	 * 登录
	 * @param Request $request
	 * @return void
	 * @throws GuzzleException
	 */
	public function login(Request $request)
	{
		
		$mini_code = $request->post('mini_code');
		$invite_code = $request->post('invite_code');
		if (empty($mini_code)) {
			$this->writeJson(0, '参数错误');
		}
		try {
			$openid = Common::getWechatOpenid($mini_code);
		} catch (\Throwable $e) {
			$this->writeJson(0,$e->getMessage());
		}
		$user = User::getByOpenid($openid);
		
		$time = time();
		$ip = $request->ip();
		$parent = false;
		if (!empty($invite_code)) {
			$parent = User::where(['invitecode' => $invite_code])->find(); //父级
		}
		// 启动事务
		Db::startTrans();
		try {
			if ($user) {
				if ($user->pid == 0 && $parent) {
					$user->pid = $parent->id;
					$invite_amount = \app\model\Config::getFieldByName('invite_amount', 'value');
					Notice::create([
						'content' => "{$parent->nickname}邀请好友赚了{$invite_amount}元"
					]);
					UserService::changeUserMoney($invite_amount, $parent->id, '邀请好友');
				}
				$user->prevtime = $user->logintime;
				$user->logintime = $time;
				$user->loginip = $ip;
				$user->save();
			} else {
				do {
					$nickname = '用户' . rand(1000000, 9999999);
				} while (User::where(['nickname' => $nickname])->find());
				do {
					$invitecode = Random::alnum();
				} while (User::where(['invitecode' => $invitecode])->find());
				$user = User::create([
					'logintime' => $time,
					'loginip' => $ip,
					'jointime' => $time,
					'joinip' => $ip,
					'nickname' => $nickname,
					'avatar' => '/assets/img/avatar.png',
					'status' => 'normal',
					'openid' => $openid,
					'invitecode' => $invitecode,
					'pid' => $parent ? $parent->id : 0
				]);
				if ($parent) {
					$invite_amount = \app\model\Config::getFieldByName('invite_amount', 'value');
					Notice::create([
						'content' => "{$parent->nickname}邀请好友赚了{$invite_amount}元"
					]);
					UserService::changeUserMoney($invite_amount, $parent->id, '邀请好友');
				}
				
			}
			Db::commit();
		} catch (\Throwable $e) {
			Db::rollback();
			$this->writeJson(0, $e->getMessage());
		}
		$token = JWTAuth::builder(['user_id' => $user->id]);
		if (empty($user->mobile)) {
			$this->writeJson(101, '请先绑定手机号', ['Authorization' => 'Bearer ' . $token]);
		}
		$this->writeJson(1, '登录成功', '', 'json', ['Authorization' => 'Bearer ' . $token]);
	}
	
	/**
	 * 绑定手机号
	 * @param Request $request
	 * @return void
	 */
	function bindMobile(Request $request)
	{
		$mobile_code = $request->post('mobile_code');
		
		if (empty($mobile_code)) {
			$this->writeJson(0, '参数错误');
		}
		
		try {
			$mobile = Common::getWechatMobile($mobile_code);
		}catch (\Throwable $e){
			$this->writeJson($e->getMessage());
		}
	
		if (User::getByMobile($mobile)) {
			$this->writeJson(0, '手机号已存在');
		}
		$user = User::findOrFail($this->user_id);
		
		$user->mobile = $mobile;
		$user->save();
		$token = JWTAuth::builder(['user_id' => $user->id]);
		$this->writeJson(1, '登录成功', '', 'json', ['Authorization' => 'Bearer ' . $token]);
	}
	
	/**
	 * 获取用户信息
	 * @return void
	 */
	function getUserInfo()
	{
		$row = User::filter(function ($data) {
			$count = GoodsOrders::where(['user_id' => $this->user_id, 'pay_status' => 2])->count();
			$point_count = PointGoodsOrders::where(['user_id' => $this->user_id, 'pay_status' => 2])->count();
			$data->tip_count = $point_count + $count;
		})->find($this->user_id);
		if (!$row) {
			$this->writeJson(401, '请先登录');
		}
		$this->writeJson($row);
	}
	
	/**
	 * 编辑个人信息
	 * @return void
	 */
	function userEdit()
	{
		$avatar = $this->request->post('avatar');
		$nickname = $this->request->post('nickname');
		$gender = $this->request->post('gender'); #1女  2男
		$birthday = $this->request->post('birthday');
		$row = User::findOrFail($this->user_id);
		if (!empty($avatar)) {
			$row->avatar = $avatar;
		}
		if (!empty($nickname)) {
			$row->nickname = $nickname;
		}
		if (!empty($gender)) {
			$row->gender = $gender;
		}
		if (!empty($birthday)) {
			$row->birthday = $birthday;
		}
		$row->save();
		$this->writeJson();
	}
	
	#积分记录
	function userScore()
	{
		$status = $this->request->get('status/d'); // 0全部 1支出 2收入
		$rows = UserScoreLog::where(['user_id' => $this->user_id])->when(!empty($status), function (Query $query) use ($status) {
			if ($status == 1) {
				$query->where('score', '<=', 0);
			} else {
				$query->where('score', '>=', 0);
			}
		})->filter(function ($data) {
			if ($data->score > 0) {
				$data->score = '+' . $data->score;
			}
		})->order(['id' => 'desc'])->paginate()->items();
		$this->writeJson($rows);
	}
	
	#收益记录
	function userMoney()
	{
		$status = $this->request->get('status/d'); // 0全部 1支出 2收入
		$rows = UserMoneyLog::where(['user_id' => $this->user_id])->when(!empty($status), function (Query $query) use ($status) {
			if ($status == 1) {
				$query->where('money', '<=', 0);
			} else {
				$query->where('money', '>=', 0);
			}
		})->filter(function ($data) {
			if ($data->money > 0) {
				$data->money = '+' . $data->money;
			}
		})->order(['id' => 'desc'])->paginate()->items();
		$this->writeJson($rows);
	}
	
	#优惠券列表
	function couponList()
	{
		$status = $this->request->get('status/d'); // 1可使用 2已使用 3已失效
		$rows = UserCoupon::where(['user_id' => $this->user_id])->where(['status' => $status])->paginate()->items();
		$status1 = UserCoupon::where(['user_id' => $this->user_id])->where(['status' => 1])->count();
		$status2 = UserCoupon::where(['user_id' => $this->user_id])->where(['status' => 2])->count();
		$status3 = UserCoupon::where(['user_id' => $this->user_id])->where(['status' => 3])->count();
		$this->writeJson(['list' => $rows, 'status1' => $status1, 'status2' => $status2, 'status3' => $status3,]);
	}
	
	#邀请海报
	function getQRCode()
	{
		$user = User::findOrFail($this->user_id);
		$invite_amount = \app\model\Config::getFieldByName('invite_amount', 'value');
		$invite_image = \app\model\Config::getFieldByName('invite_image', 'value');
		$list = Notice::order(['id' => 'desc'])->limit(10)->select();
		try {
			$res = Common::getWechatQrcode('pages/index/index',$user->invitecode);
		} catch (\Throwable $e) {
			$this->writeJson($e->getMessage());
		}
		$this->writeJson(['qrcode' => 'data:image/png;base64,' . base64_encode($res), 'invite_amount' => $invite_amount, 'invite_image' => $invite_image, 'invitecode' => $user->invitecode, 'notice_list' => $list]);
	}
	
	#收藏列表
	function collectList()
	{
		$good_ids = UserCollect::where(['user_id' => $this->user_id])->column('goods_id');
		$rows = Goods::withMin(['spec' => 'min_price'], 'price')->whereIn('id', $good_ids)->paginate()->items();
		$this->writeJson($rows);
	}
	
	#足迹列表
	function footList()
	{
		$status = $this->request->get('status/d'); // 1今天 2昨天 3近七天 4近30天 5自定义
		$startdate = $this->request->get('startdate');
		$enddate = $this->request->get('enddate');
		$date = [];
		switch ($status) {
			case 1:
				$goods_ids = UserFoot::where(['user_id' => $this->user_id])->whereDay('createtime')->column('goods_id');
				$rows = Goods::withMin(['spec' => 'min_price'], 'price')->whereIn('id', $goods_ids)->select();
				$date[] = ['day' => date('Y-m-d'), 'list' => $rows];
				break;
			case 2:
				$goods_ids = UserFoot::where(['user_id' => $this->user_id])->whereDay('createtime', 'yesterday')->column('goods_id');
				$rows = Goods::withMin(['spec' => 'min_price'], 'price')->whereIn('id', $goods_ids)->select();
				$date[] = ['day' => date('Y-m-d', strtotime("yesterday")), 'list' => $rows];
				break;
			case 3:
				for ($i = 0; $i <= 6; $i++) {
					$day = date('Y-m-d', strtotime("-{$i} day"));
					$goods_ids = UserFoot::where(['user_id' => $this->user_id])->whereDay('createtime', $day)->column('goods_id');
					$rows = Goods::withMin(['spec' => 'min_price'], 'price')->whereIn('id', $goods_ids)->select();
					$date[] = ['day' => $day, 'list' => $rows];
				}
				break;
			case 4:
				for ($i = 0; $i <= 29; $i++) {
					$day = date('Y-m-d', strtotime("-{$i} day"));
					$goods_ids = UserFoot::where(['user_id' => $this->user_id])->whereDay('createtime', $day)->column('goods_id');
					$rows = Goods::withMin(['spec' => 'min_price'], 'price')->whereIn('id', $goods_ids)->select();
					$date[] = ['day' => $day, 'list' => $rows];
				}
				break;
			case 5:
				$start_date = new DateTime($startdate);
				$end_date = new DateTime($enddate);
				$end_date->modify('+1 day'); // 包括结束日期
				$date_interval = new DateInterval('P1D'); // 间隔为1天
				$date_range = new DatePeriod($start_date, $date_interval, $end_date);
				$days = [];
				foreach ($date_range as $item) {
					$days[] = $item->format('Y-m-d');
					
				}
				$days = array_reverse($days);
				foreach ($days as $day) {
					$goods_ids = UserFoot::where(['user_id' => $this->user_id])->whereDay('createtime', $day)->column('goods_id');
					$rows = Goods::withMin(['spec' => 'min_price'], 'price')->whereIn('id', $goods_ids)->select();
					$date[] = ['day' => $day, 'list' => $rows];
				}
				break;
			default:
				$this->writeJson(0, '参数错误');
		}
		$this->writeJson($date);
	}
	
	function footClear()
	{
		$status = $this->request->post('status/d'); // 1今天 2昨天 3近七天 4近30天 5自定义
		$startdate = $this->request->post('startdate');
		$enddate = $this->request->post('enddate');
		
		switch ($status) {
			case 1:
				UserFoot::destroy(function (Query $query) {
					$query->where(['user_id' => $this->user_id])->whereDay('createtime');
				});
				break;
			case 2:
				UserFoot::destroy(function (Query $query) {
					$query->where(['user_id' => $this->user_id])->whereDay('createtime', 'yesterday');
				});
				break;
			case 3:
				for ($i = 0; $i <= 6; $i++) {
					$day = date('Y-m-d', strtotime("-{$i} day"));
					UserFoot::destroy(function (Query $query) use ($day) {
						$query->where(['user_id' => $this->user_id])->whereDay('createtime', $day);
					});
				}
				break;
			case 4:
				for ($i = 0; $i <= 29; $i++) {
					$day = date('Y-m-d', strtotime("-{$i} day"));
					UserFoot::destroy(function (Query $query) use ($day) {
						$query->where(['user_id' => $this->user_id])->whereDay('createtime', $day);
					});
				}
				break;
			case 5:
				$start_date = new DateTime($startdate);
				$end_date = new DateTime($enddate);
				$end_date->modify('+1 day'); // 包括结束日期
				$date_interval = new DateInterval('P1D'); // 间隔为1天
				$date_range = new DatePeriod($start_date, $date_interval, $end_date);
				$days = [];
				foreach ($date_range as $item) {
					$days[] = $item->format('Y-m-d');
					
				}
				$days = array_reverse($days);
				foreach ($days as $day) {
					UserFoot::destroy(function (Query $query) use ($day) {
						$query->where(['user_id' => $this->user_id])->whereDay('createtime', $day);
					});
				}
				break;
			default:
				$this->writeJson(0, '参数错误');
		}
		$this->writeJson();
	}
	
	#收入统计
	function todayData()
	{
		$user = User::find($this->user_id);
		if (!$user) {
			$this->writeJson(401, '重新登陆');
		}
		if ($user->type != 2) {
			$this->writeJson(0, '你没有核销权限');
		}
		$today_order_money = AdminMoneyLog::where(['type' => 1])->whereTime('createtime', 'today')->sum('amount');
		$today_vip_money = AdminMoneyLog::where(['type' => 2])->whereTime('createtime', 'today')->sum('amount');
		$list = AdminMoneyLog::with(['user'])->whereTime('createtime', 'today')->paginate()->items();
		$this->writeJson(['today_order_money' => $today_order_money, 'today_vip_money' => $today_vip_money, 'list' => $list]);
	}
	
	
}
